package com.example.myapplication

import android.content.Intent
import android.media.session.MediaSession
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.myapplication.model.ResultOV
import com.example.myapplication.model.Student
import com.example.myapplication.service.StudentService
import com.example.myapplication.utils.FileUtil
import com.example.myapplication.utils.HttpUtil
import com.example.myapplication.utils.ServerCreator
import com.google.gson.Gson


import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.io.IOException
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        submit.setOnClickListener {
            // val data="username=${et_username.text.toString()}&password=${et_password.text.toString()}"
            // startActivity(Intent(this,FifthActivity::class.java))
            val intentOk: Intent = Intent(this, SecondActivity::class.java)
            val intentError: Intent = Intent(this, ThirdActivity::class.java)
            val requestData = HashMap<String, String>()
            requestData.put("username", et_username.text.toString())
            requestData.put("password", et_password.text.toString())
            // sendRequestWithHttpURLConnection(data)
            //  sendRequestWithOkHttp("http://106.15.192.167:8080/userLogin","post",requestData)
         HttpUtil.sendOkHttpRequest("http://10.17.218.37:9100/StudentSystem/UserLogin",requestData,
          object:Callback{
              override fun onFailure(call: Call, e: IOException) {
                 Log.e("MainActivity","发生错误了")
                  e.printStackTrace();
              }

              override fun onResponse(call: Call, response: Response) {
                  val resultData=response.body?.string()
                  var fromgson=Gson().fromJson<ResultOV>(resultData,ResultOV::class.java)
                  if(fromgson.result=="ok"){
                        startActivity(intentOk)
                  }else{
                     startActivity(intentError)
                  }
              }
        })
        }
                    button2.setOnClickListener() {
                val intent = Intent(this, FourthActivity::class.java)
                startActivity(intent)
    }
        button6.setOnClickListener(){
            val  intent=Intent(this,ImageActivity::class.java)
            startActivity(intent)
        }
        button7.setOnClickListener(){
            val intent =Intent(this,RegisterActivity::class.java)
            startActivity(intent)
        }
}}
//            val studentService = ServerCreator.create<StudentService>();
////2. 调用实例对象方法，由于需要网络请求，需要继续调用enqueue方法
//            studentService.getStudentData().enqueue(object : retrofit2.Callback<List<Student>> {
//                override fun onFailure(call: retrofit2.Call<List<Student>>, t: Throwable) {
//                    t.printStackTrace()
//                }
//
//                //3. 请求成功！
//                override fun onResponse(
//                    call: retrofit2.Call<List<Student>>,
//                    response: retrofit2.Response<List<Student>>
//                ) {
//                    val user = response.body()
//                    if (user != null){
//                        startActivity(intentOk)
//                    }
//
//            } })
//            button2.setOnClickListener() {
//                val intent = Intent(this, FourthActivity::class.java)
//                startActivity(intent)
//            }}}}
// private fun sendRequestWithOkHttp(
//                url: String,
//                method: String,
//                data: Map<String, String>
//            ) {
//                thread {
//                    try {
//                        val client = OkHttpClient()
//                        val username = data.get("username").toString()
//                        val password = data.get("password").toString()
//                        val requestBody = FormBody.Builder()
//                            .add("username", username)
//                            .add("password", password)
//                            .build()
//                        val request = Request.Builder()
//                            .url(url)
//                            .post(requestBody)
//                            .build()
//                        val response = client.newCall(request).execute()
//                        val responseData = response.body?.string()
//                        if (responseData != null) {
//                            dealResponse(responseData)
//                        }
//
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }
//                }
//
//            }
//
//           private fun dealResponse(responseData: String) {
//                //    Log.d("MainActvity",responseData)
//                // Toast.makeText(this,responseData,Toast.LENGTH_LONG).show()
//                var result = Gson().fromJson(responseData, ResultOV::class.java)
//                if (result.result == "ok") {
//                    //跳转到second页面
//                    val intentOk: Intent = Intent(this, SecondActivity::class.java)
//                    startActivity(intentOk)
//                } else {
//                    //跳转到third页面
//                    val intentError: Intent = Intent(this, ThirdActivity::class.java)
//                    startActivity(intentError)
//                }
//            }
//
//                /*
//    * android 网络编程
//    * httpUrlConnection
//    * var  url=URL("http://106.15.192.167/userLogin")
//    * var conn =url.openConnection() as HttpURLConnection
//    * conn.requestMethod="POST"
//    * conn.ConnectionTimeout=8000
//    * conn.readTimeout=8000
//    *     * */
//            private fun sendRequestWithHttpURLConnection(data: String): Unit {
//                //开启一个线程
//                thread {
//                    var conn: HttpURLConnection? = null
//                    try {
//                        //获取连接
//                        val url = URL("http://106.15.192.167:8080/userLogin")
//                        conn = url.openConnection() as HttpURLConnection
//                        //设置参数
//                        conn.requestMethod = "POST"
//                        conn.connectTimeout = 8000
//                        conn.readTimeout = 8000
//                        //获取输出流
//                        var output = conn.outputStream
//                        output.write(data.toByteArray())
//                        //立即发送
//                        output.flush()
//                        //获取发送状态码
//                        var responseCode = conn.responseCode
//                        //对发送码进行判断
//                        if (responseCode == 200) {
//                            //接收数据
//                            var input = conn.inputStream
//                            var result = FileUtil.getStringFromInputStream(input)
//                            Log.e("MainActivity", result)
//                            var resultOV = Gson().fromJson<ResultOV>(result, ResultOV::class.java)
//                            if (resultOV.result == "ok") { //登录成功
//                                //跳转到second页面
//                                val intentOk: Intent = Intent(this, SecondActivity::class.java)
//                                startActivity(intentOk)
//                            } else {
//                                //跳转到third页面
//                                val intentError: Intent = Intent(this, ThirdActivity::class.java)
//                                startActivity(intentError)
//                            }
//
//                        }
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }
//                }
//            }
//
//        }
//    }}